const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const router = require('koa-router')()

const multer = require('koa-multer')
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, './public/uploads/')
  },
  filename: function (req, file, cb) {
    const fileFormat = (file.originalname).split(`.`)
    cb(null, `${Date.now()}.${fileFormat[fileFormat.length - 1]}`)
  }
})
const upload = multer({storage: storage})
// error handler
onerror(app)

// middlewares
app.use(bodyparser({
  enableTypes: ['json', 'form', 'text']
}))
app.use(json())
app.use(logger())
app.use(require('koa-static')(`${__dirname}/public`))

app.use(views(`${__dirname}/views`, {
  extension: 'pug'
}))

const options = { // 设置连接池，自动连接，否则可能会出现：topology was destroyed
  // auto_reconnect: true,
  poolSize: 10,
  reconnectTries: 30,
  reconnectInterval: 3000
}
const mongoose = require('mongoose')
mongoose.Promise = global.Promise
mongoose.connect('mongodb://localhost/beta_data', options)
mongoose.connection.on('error', console.log.bind(console, '连接mongoDb数据库错误'))
mongoose.connection.on('open', console.log.bind(console, '连接数据库成功'))

// 加载models
require('./app/models/group')
require('./app/models/sprint')
require('./app/models/log')

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

app.use(async (ctx, next) => {
  ctx.set('Access-Control-Allow-Origin', 'http://localhost:8080')
  ctx.set('Access-Control-Allow-Credentials', 'true')
  ctx.set('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept')
  await next()
})

// 处理路由
require('./routes/index')(router, upload)

// routes
// app.use(index.routes(), index.allowedMethods())
// app.use(users.routes(), users.allowedMethods())
app
  .use(router.routes())
  .use(router.allowedMethods())

// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
})

module.exports = app
